/**
 * Created by George on 2019/6/3.
 */

function paginationDirective() {
    return {
        restrict: 'E',
        scope: {
            totalCount: '=',
            pageSize: '=',
            currentPage: '=',
            pageItems: '=',
            goPage: '&'
        },
        controller: controller,
        templateUrl: "views/components/pagination.html"
    };

    function controller($scope) {
        $scope.totalPage = Math.ceil($scope.totalCount / $scope.pageSize);
        $scope.pageList = getPages($scope.totalPage, $scope.currentPage);
        //跳转到某一页
        function goPage() {
            let params = {
                pageSize: $scope.pageSize,
                pageNo: $scope.currentPage,
            };
            $scope.goPage(params);
        }

        $scope.setCurrentPage = function (pageNo) {
            if (pageNo === '...' || pageNo === 0 || pageNo > $scope.totalPage || pageNo === '') {
                return;
            }
            $scope.currentPage = pageNo;
            $scope.pageList = getPages($scope.totalPage, $scope.currentPage);
            goPage();
        };

        //每页显示size改变
        $scope.changeSize = function () {
            initDefaultPages();
            goPage();
        };

        function initDefaultPages() {
            $scope.currentPage = 1;
            $scope.totalPage = Math.ceil($scope.totalCount / $scope.pageSize);
            $scope.pageList = getPages($scope.totalPage, $scope.currentPage);
        }

        $scope.$watch('currentPage', function () {
            $scope.pageList = getPages($scope.totalPage, $scope.currentPage);
        });

        $scope.$watch('totalCount', function () {
            initDefaultPages();
        });
        $scope.$watch('pageSize', function () {
            initDefaultPages();
        });

        function getPages(totalPage, currentPage) {
            currentPage = Math.min(totalPage, currentPage);
            var pages = [];
            if (totalPage <= 1) {
                pages.push(1);
            }
            else if (totalPage <= 4) {
                for (var index = 1; index <= totalPage; index++) {
                    pages.push(index);
                }
            } else {
                if (currentPage != 1) {
                    pages.push(1);
                }

                if (currentPage > 3) {
                    pages.push("...");
                }
                if (currentPage > 2) {
                    pages.push(currentPage - 1);
                }
                pages.push(currentPage);
                if (currentPage + 1 < totalPage) {
                    pages.push(currentPage + 1);
                }
                if (currentPage + 2 < totalPage) {
                    pages.push("...");
                }

                if (currentPage != totalPage) {
                    pages.push(totalPage);
                }
            }
            return pages;
        }
    }

}

export default paginationDirective;
